package br.org.imazon.sad;

import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class SearchServlet extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException {
    try {
      // Get authenticated access to the Fusion Tables containing the polygons.
      HttpSession session = req.getSession();
      String auth = Authenticate.auth(session, "fusiontables");
      FusionTablesAccess access = new FusionTablesAccess(auth);

      // Query all the tables for polygons with matching descriptions.
      HashMap<String, String> tables = access.getTables();
      ArrayList<HashMap<String, String>> polygons =
          access.getPolygons(req.getQueryString(), tables);
      
      // Return the results to the browser, encoded as JSON.
      resp.setCharacterEncoding("UTF-8");
      resp.getWriter().print((new Gson()).toJson(polygons)); 
    } catch (AuthenticationException e) {
      resp.setStatus(403);
      resp.getOutputStream().print(e.getMessage());
    } catch (ServiceException e) {
      resp.setStatus(500);
      resp.getOutputStream().print(e.getMessage());
    }
  }
}